package cn.itcast.bos.service.impl.system;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.system.MenuRepository;
import cn.itcast.bos.dao.system.PermissionRepository;
import cn.itcast.bos.dao.system.RoleRepository;
import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.service.system.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleRepository roleRepository;

	@Autowired
	private PermissionRepository permissionRepository;
	@Autowired
	private MenuRepository menuRepository;

	@Override
	public List<Role> findByRole() {
		// TODO Auto-generated method stub
		return roleRepository.findAll();
	}

	@Override
	public void saveRole(Role role, String[] permissionIds, String menuIds) {
		// TODO Auto-generated method stub
		// 1.保存角色
		roleRepository.save(role);// 持久态
		// 2.关联功能权限：持久态关联
		if (permissionIds != null) {
			for (String permissionId : permissionIds) {

				Integer id = Integer.parseInt(permissionId);
				Permission permission = permissionRepository.findOne(id);
				// 建立关联
				role.getPermissions().add(permission);
				// 等flush
			}
		}
		// 3.关联角色:持久态关联
		if (StringUtils.isNotBlank(menuIds)) {
			// 以,号切割
			String[] menuIdArr = menuIds.split(",");
			for (String menuId : menuIdArr) {
				Menu menu = menuRepository.findOne(Integer.parseInt(menuId));

				// 建立关联
				role.getMenus().add(menu);
			}
			// 等flush
		}

	}

}
